# Create your views here.

from django.http import HttpResponse
from django.http import HttpResponseRedirect

from market.authentification import authentificatePlayer, authentificateUser
from django.utils import simplejson
from market.models import UserProfile


#######################################################

#### YOU HAVE TO IMPORT THE FUNCTION (cf functio in jsonForCharts)

######################################################
from market.jsonsForCharts import getPlayerMainViewData
from market.jsonsForCharts import getPlayerMainViewData2
from market.jsonsForCharts import getMtMsHistory
from market.jsonsForCharts import getPricesHistory
from market.jsonsForCharts import getRankingTableData
from market.jsonsForCharts import getPlayerInvestementRepartition
from market.jsonsForCharts import getComments
from market.jsonsForCharts import getMarketView
from market.jsonsForCharts import getMarketPrices
from market.jsonsForCharts import getAssets
from market.jsonsForCharts import getAssetsAll
from market.jsonsForCharts import getBetroomsToPlay
from market.jsonsForCharts import getBetroomsToAdmin
from market.jsonsForCharts import getBetroomsBeingLaunched
from market.jsonsForCharts import getBetroomDescription
from market.jsonsForCharts import getPlayerList
from market.jsonsForCharts import getContracts
from market.jsonsForCharts import getUnsettledContracts
from market.jsonsForCharts import getSelectedContractInfo
from market.jsonsForCharts import getAllContractsInfo

import ast
import inspect


#######################################################################################
# gets all jsons for table and charts
def getAllJsonsForTablesAndCharts(request):
	# get the request details
	listOfRequests = {}
        try:
                listOfRequests0 = ast.literal_eval( request.POST["callsList"] )
                listOfRequests = listOfRequests0["callsList"]
        except:
                return HttpResponse( "callsList field missing in the requet. Alternatively, it is not a dictionary containing callsList entry" )

        # for all elmts in the request call the appropriate func
        errorList = []
        resList = []
        module = __import__ ('market.jsonsForCharts')
        for r in listOfRequests:
                res = {}
                resOk = 1
                name = ""
                try:
                        name = r["pyFuncName"]
                        func = globals()[name]
                        res = {'py_name': func(request), 'js_name':r["jsFuncName"] }
                except:
                        errorList.append( "error calling %s" %name )
                        resOk = 0
                # we only add the result when it looks ok
                if( resOk == 1  ):
                        resList.append( res )
        #as the result of this request is handled in java script, we return the results we have even if we have some faillure
        # this allow to display th graphs for wichh there is no faiulure instead of diplaying nothing
        return HttpResponse(simplejson.dumps(resList), mimetype='application/javascript')


#######################################################################################
# returns the dictionary of the visible functions whose argument is "request"
def getDictionnaryOfAvaiableFunc():
        res = []
        for f in globals().keys():
                if f != 'getAllJsonsForTablesAndCharts' and f != 'getSpecificJson' :
                        obj = globals()[f]
                        if( callable( obj ) ):
                                try:
                                        listArg =  inspect.getargspec(obj)
                                        if len( listArg[0] ) == 1:
                                                if( listArg[0][0] == 'request' ):
                                                        res.append( f )
                                except:
                                        pass
        return res


       
#######################################################################################
# allows to visualize a json into the web browser
def getSpecificJson(request):
        
        funcs = getDictionnaryOfAvaiableFunc()
	try:
                try:
                        funcName = request.GET['func']
                except:
                        funcName = request.POST['func']

                if not( funcName in funcs ):
                        raise Exception( '' )
                func = globals()[funcName]
                if( not( callable( func ) ) ):
                      raise Exception( '' )

        # if the name does not exist, we suggest all the function which argument list is only player
        except:
                response = HttpResponse(mimetype='text/plain')        
                response.write( "maybe try one of the following url. <br/>This is the list of al visible functions having \"request\" for argument: <br/> " )
                for f in funcs:
                        response.write("/json/getSpecificJson/?func="+ f+"<br/>")
                return HttpResponse( response )

        return HttpResponse(simplejson.dumps([func(request)]), mimetype='application/javascript')




